import json
import os
import threading

from flask import Flask, render_template, jsonify, request, send_file

import paramsConfig
from command import CommandExcute
from docxgen import DocxHandle
from fileconfig import FileConfigPath, CityParamClass
from log import InspectionGenAutoLogs
from sshcon import sshConnector

app = Flask(__name__)

# 注册参数配置页面
app.add_url_rule('/params/config', view_func=paramsConfig.paramsConfig)
app.add_url_rule('/params/uploadFiles', view_func=paramsConfig.uploadFiles, methods=['GET', 'POST'])
app.add_url_rule('/params/download/<fileType>/<fileName>', view_func=paramsConfig.downloadFile, methods=['POST'])


@app.route('/')
def index():
    # 从log 表查询数据
    result = InspectionGenAutoLogs.InspectionGenAutoLogs.select_data_limit10()
    return render_template('index.html', result=result)


@app.route('/gen/doxc', methods=['GET', 'POST'])
def genDocx():
    if request.method == 'POST':
        docxFileName = request.form['docxConfig']
        commandFileName = request.form['commandConfig']
        fixedFileName = request.form['fixedConfig']
        aiFileName = request.form['AIConfig']
        cityFileName = request.form['cityConfig']
        city = request.form.getlist('city')
        # 如果其中有值为空，则返回错误
        if docxFileName == '-' or commandFileName == '-' or fixedFileName == '-' or aiFileName == '-' or cityFileName == '-':
            return '必填参数不能为空'
        print(docxFileName, commandFileName, fixedFileName, aiFileName, city)
        for item in city:
            # 调用后端的自动化部署脚本
            template_name = "系统巡检报告_" + item + '.docx'
            # 将参数封装成json 数据
            jsonObject = {
                "city": item,
                "docxFileName": docxFileName,
                "commandFileName": commandFileName,
                "fixedFileName": fixedFileName,
                "aiFileName": aiFileName,
                "cityFileName": cityFileName
            }
            json_string = json.dumps(jsonObject)
            # 插入日志
            logsId = InspectionGenAutoLogs.InspectionGenAutoLogs.init_default(item, template_name, json_string)
            # 多线程处理
            thread = threading.Thread(target=processEngine,
                                      args=(
                                          item, docxFileName, commandFileName, fixedFileName, aiFileName, cityFileName,
                                          template_name, logsId))
            # 启动线程
            thread.start()
            return "任务已经提交，请等待"
    return index()


# 调用巡检生成流程
def processEngine(item, docxFileName, commandFileName, fixedFileName, aiFileName, cityFileName, template_name, logsId):
    # 组装配置文件路径
    commandParamsPath = os.path.join(FileConfigPath.command_params_path, commandFileName)
    aiParamsPath = os.path.join(FileConfigPath.ai_params_path, aiFileName)
    newFilePath = os.path.join(FileConfigPath.gen_docx_path, template_name)
    cityFilePath = os.path.join(FileConfigPath.city_params_path, cityFileName)
    docFilePath = os.path.join(FileConfigPath.docx_template_path, docxFileName)
    fixedFilePath = os.path.join(FileConfigPath.fixed_params_path, fixedFileName)
    # 配置文件参数化
    need_to_dict = FileConfigPath.need_to_dict(cityFilePath, item)
    # 获得ssh连接
    ssh = sshConnector.connect(item, cityFilePath)
    InspectionGenAutoLogs.InspectionGenAutoLogs.updateStatus(logsId, '生成中')
    commandResult = CommandExcute.getInspectionCommandResult(ssh, commandParamsPath, aiParamsPath)
    print(commandResult)
    DocxHandle.getInspectionDocx(need_to_dict, commandResult, docFilePath, fixedFilePath, newFilePath, aiParamsPath)
    InspectionGenAutoLogs.InspectionGenAutoLogs.updateStatus(logsId, '生成完成')


@app.route('/ConfigSelect/<fileType>')
def docxConfigSelectSelect(fileType):
    if fileType == 'docx':
        files = os.listdir(FileConfigPath.docx_template_path)
    if fileType == 'fixed':
        files = os.listdir(FileConfigPath.fixed_params_path)
    if fileType == 'command':
        files = os.listdir(FileConfigPath.command_params_path)
    if fileType == 'ai':
        files = os.listdir(FileConfigPath.ai_params_path)
    if fileType == 'city':
        files = os.listdir(FileConfigPath.city_params_path)
    filesName = []
    for file in files:
        filesName.append(file)
    print(filesName)
    return filesName


@app.route('/citySelect/<cityParamsPath>')
def citySelect(cityParamsPath):
    resultList = []
    with open(FileConfigPath.city_params_path + "/" + cityParamsPath, 'r', encoding='utf-8') as f:
        cityParams = json.load(f)
        # 获取城市名称列表
        cityList = cityParams.get('data')
        # 遍历cityList，找到 city 名称是传入的
        for item in cityList:
            resultList.append(jsonify(CityParamClass.CityParamClass.city_to_dict(
                CityParamClass.CityParamClass(item.get('city'), item.get('city_name')))).get_json())
    print(resultList)
    return resultList


@app.route('/download/<fileName>')
def downloadDocxFile(fileName):
    filenamePath = os.path.join(FileConfigPath.gen_docx_path, fileName)
    return send_file(filenamePath, as_attachment=True)


if __name__ == '__main__':
    app.run(port=5200, host='0.0.0.0', debug=True)
